package com.ticket.web.controller.yanchu;

import com.google.common.collect.Lists;
import com.ticket.common.annotation.Log;
import com.ticket.common.core.controller.BaseController;
import com.ticket.common.core.domain.AjaxResult;
import com.ticket.common.core.domain.entity.SysUser;
import com.ticket.common.core.page.TableDataInfo;
import com.ticket.common.enums.BusinessType;
import com.ticket.common.utils.DateUtils;
import com.ticket.common.utils.StringUtils;
import com.ticket.framework.web.service.TokenService;
import com.ticket.system.domain.YanchuMovieBatch;
import com.ticket.system.domain.vo.CardUserInfoVO;
import com.ticket.system.service.ISysUserService;
import com.ticket.system.service.IYanchuMovieBatchService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 观演卡批次信息Controller
 * 
 * @author ruoyi
 * @date 2023-12-07
 */
@Api(description = "观演卡批次信息")
@RestController
@RequestMapping("/system/batch")
public class YanchuMovieBatchController extends BaseController
{
    @Autowired
    private IYanchuMovieBatchService yanchuMovieBatchService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation("查询观演卡批次信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchName",value = "批次名称",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "amount",value = "面值",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "status",value = "当前状态（0：待激活；1：已激活）",dataType = "Integer",dataTypeClass = Integer.class),
    })
    @PreAuthorize("@ss.hasPermi('system:batch:list')")
    @GetMapping("/list")
    public TableDataInfo list(YanchuMovieBatch yanchuMovieBatch)
    {
        startPage();
        List<YanchuMovieBatch> list = yanchuMovieBatchService.selectYanchuMovieBatchList(yanchuMovieBatch);
        if (!CollectionUtils.isEmpty(list)){
            List<Long> creatIds = list.stream().map(YanchuMovieBatch::getCreatId).collect(Collectors.toList());
            List<CardUserInfoVO> cardUserInfos = sysUserService.getUserNameByIds(creatIds);
            if (!CollectionUtils.isEmpty(cardUserInfos)){
                list.forEach(y ->{
                    cardUserInfos.forEach(c ->{
                        if (y.getCreatId().equals(c.getUserId())){
                            y.setCreatName(c.getUserName());
                        }
                    });
                });
            }
        }
        return getDataTable(list);
    }

    @ApiOperation("导出观演卡（按批次导出）")
    @PreAuthorize("@ss.hasPermi('system:batch:export')")
    @Log(title = "观演卡批次信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YanchuMovieBatch yanchuMovieBatch)
    {
        List<Long> batchIds = Lists.newArrayList();
        if (StringUtils.isNotEmpty(yanchuMovieBatch.getBatchIds())){
            batchIds = Arrays.stream(yanchuMovieBatch.getBatchIds().split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        }else {
            List<YanchuMovieBatch> yanchuMovieBatches = yanchuMovieBatchService.selectYanchuMovieBatchList(yanchuMovieBatch);
            if (!CollectionUtils.isEmpty(yanchuMovieBatches)){
                batchIds = yanchuMovieBatches.stream().map(YanchuMovieBatch::getId).collect(Collectors.toList());
            }
        }
        yanchuMovieBatchService.export(batchIds,response);
    }

    @ApiOperation("获取观演卡名称")
    @GetMapping("/getCardName")
    public AjaxResult getCardName()
    {
        return success(yanchuMovieBatchService.getCardName());
    }

    @ApiOperation("新增观演卡批次")
    @ApiImplicitParam(name = "yanchuMovieBatch",value = "观演卡批次实体",dataTypeClass = YanchuMovieBatch.class,dataType = "YanchuMovieBatch")
    @PreAuthorize("@ss.hasPermi('system:batch:add')")
    @Log(title = "观演卡批次信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Valid YanchuMovieBatch yanchuMovieBatch)
    {
        return toAjax(yanchuMovieBatchService.insertYanchuMovieBatch(yanchuMovieBatch));
    }

    @ApiOperation("观演卡详情")
    @PreAuthorize("@ss.hasPermi('system:batch:query')")
    @Log(title = "观演卡批次信息", businessType = BusinessType.UPDATE)
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        YanchuMovieBatch batch = yanchuMovieBatchService.selectYanchuMovieBatchById(id);
        List<Long> userIds = Lists.newArrayList();
        userIds.add(batch.getCreatId());
        userIds.add(batch.getActiveId());
        List<CardUserInfoVO> cardUserInfos = sysUserService.getUserNameByIds(userIds);
        if (!CollectionUtils.isEmpty(cardUserInfos)){
            cardUserInfos.forEach(c ->{
                if (c.getUserId().equals(batch.getCreatId())){
                    batch.setCreatName(c.getUserName());
                }
                if (c.getUserId().equals(batch.getActiveId())){
                    batch.setActiveName(c.getUserName());
                }
            });
        }
        return success(batch);
    }

    @ApiOperation("设置有效期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchIds",value = "批次id 多个逗号拼接",dataType = "Long",dataTypeClass = Long.class),
            @ApiImplicitParam(name = "cardIds",value = "卡号id 多个逗号拼接",dataType = "String",dataTypeClass = String.class),
            @ApiImplicitParam(name = "time",value = "有效期",required = true,dataType = "String",dataTypeClass = String.class),
    })
    @PostMapping("/updateValidTime")
    public AjaxResult updateValidTime(String batchIds, String cardIds,@RequestParam String time){
        yanchuMovieBatchService.updateValidTime(batchIds,cardIds, DateUtils.parseDate(time));
        return success();
    }

    @ApiOperation("批次激活")
    @ApiImplicitParam(name = "batchIds",value = "批次id 多个逗号拼接",required = true,dataTypeClass = Long.class,dataType = "long")
    @PostMapping("/activeBatch")
    public AjaxResult activeBatch(String batchIds, HttpServletRequest request){
        SysUser user = tokenService.getLoginUser(request).getUser();
        yanchuMovieBatchService.activeBatch(batchIds,user.getUserId(),user.getNickName());
        return success();
    }
}
